package com.common.queueloader.items
{
	import com.common.queueloader.AbstractItem;
	import com.common.queueloader.ILoadable;
	import com.common.queueloader.QueueVo;
	import com.common.zip.fzip.FZip;
	
	import flash.display.Loader;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	/**
	 *加载swc文件 
	 * @author lake
	 * 
	 */	
	public class SwcItem extends AbstractItem implements ILoadable
	{
		private var fZipLoader :FZip;
		
		public function SwcItem(queueVo:QueueVo, path:URLRequest, fileType:int=0)
		{
			super(queueVo, path, fileType);
		}
		override public function load() : void 
		{
			fZipLoader = new FZip();
			fZipLoader.load(path);
			fZipLoader.addEventListener(Event.COMPLETE, onSwcLoadComplete);
			fZipLoader.addEventListener(ProgressEvent.PROGRESS,onProgress);
		}
		/**
		 *加载swc完毕
		 * @param evt
		 *
		 */        
		private function onSwcLoadComplete(evt:Event):void
		{
			var swfData :ByteArray = fZipLoader.getFileByName("library.swf").content;//取swf内容
			fZipLoader.removeEventListener(Event.COMPLETE, onComplete);
			fZipLoader  = null;
			//
			_loader = new Loader();
			var applicationDomain :ApplicationDomain = queueVo.applicationDomain;
			if(applicationDomain == null)
			{
				applicationDomain = ApplicationDomain.currentDomain;
			}
			var context:LoaderContext = new LoaderContext(false,applicationDomain)
			_loader.loadBytes(swfData,context);//加载到域
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
		}
		override public function dispose() : void 
		{
			_progress = 0;
			_bytesLoaded = 0;
			_bytesTotal = 0;
			_queueVo = null;
			_path = null;
			_isLoading = false;
			_fileType = 0;
			_loader = null;
			_httpStatusFunction = null;
			_errorFunction = null;
			_completeFunction = null;
			_progressFunction = null;
		}
		
		override public function close():void
		{
			if(_loader)
			{
				Loader(_loader).unloadAndStop(true);
			}
		}
		
		override public function onComplete(evt:Event):void 
		{
			_content = evt.target.content;
			_completeFunction(evt);
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
			_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS , onProgress);
			this.dispose();
		}
		override public function onProgress(evt:ProgressEvent):void
		{
			if(_progressFunction==null)return;
			_bytesLoaded = evt.bytesLoaded;
			_bytesTotal = evt.bytesTotal;
			_progress = Math.floor(evt.bytesLoaded / evt.bytesTotal * 100 );
			_progressFunction(evt.clone());
		}
		override public function onHttpStatus(evt:HTTPStatusEvent):void
		{
			
		}
		override public function onError(evt:ErrorEvent):void
		{
			
		}
	}
}